package com.example.qincetest.network

import android.annotation.SuppressLint
import android.content.Context
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit

class OkHttpConfig {
    companion object {
        private const val TIMEOUT_SECONDS = 10L
        private const val CACHE_SIZE = 10 * 1024 * 1024L // 10 MB
        @SuppressLint("StaticFieldLeak")
        private var context: Context? = null
        
        private val okHttpClient by lazy {
            createOkHttpClient()
        }

        fun init(appContext: Context) {
            context = appContext.applicationContext
        }
        
        private fun createCache(): Cache {
            val cacheDir = File(context?.cacheDir, "okhttp_cache")
            if (!cacheDir.exists()) {
                cacheDir.mkdirs()
            }
            return Cache(cacheDir, CACHE_SIZE)
        }
        
        private fun createOkHttpClient(): OkHttpClient {
            return OkHttpClient.Builder()
                .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .cache(createCache())
                .addInterceptor { chain ->
                    Timber.e("1. Application Interceptor: 总是被调用，包括缓存响应")
                    val request = chain.request()
                    chain.proceed(request)
                }
                .addNetworkInterceptor { chain ->
                    Timber.e("2. Network Interceptor: 只在实际发生网络请求时调用")
                    val response = chain.proceed(chain.request())
                    response.newBuilder()
                        .header("Cache-Control", "public, max-age=600")
                        .removeHeader("Pragma")
                        .build()
                }
                .build()
        }

        fun getBaiduApi() {
            val request = Request.Builder()
                .url("https://www.baidu.com/")
                .header("Cache-Control", "public, max-age=60")  // 优先使用缓存
                .build()

            okHttpClient.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    response.use {
                        if (!response.isSuccessful) throw IOException("Unexpected code $response")
                        
                        val responseData = response.body?.string()
                        Timber.e("是否来自缓存: ${response.cacheResponse != null}")
                        Timber.e("是否来自网络: ${response.networkResponse != null}")
                        Timber.e("Cache-Control: ${response.header("Cache-Control")}")
                        Timber.e("缓存目录大小: ${okHttpClient.cache?.size() ?: 0}")
                    }
                }
            })
        }

        // 添加一个强制使用网络的方法用于测试
        fun getBaiduApiForceNetwork() {
            val request = Request.Builder()
                .url("https://www.baidu.com/")
                .cacheControl(CacheControl.FORCE_NETWORK)
                .build()

            okHttpClient.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    response.use {
                        Timber.e("强制网络请求响应码: ${response.code}")
                        Timber.e("是否来自缓存: ${response.cacheResponse != null}")
                        Timber.e("是否来自网络: ${response.networkResponse != null}")
                    }
                }
            })
        }

        fun clearCache() {
            try {
                okHttpClient.cache?.evictAll()
                Timber.e("缓存已清空")
            } catch (e: Exception) {
                e.printStackTrace()
                Timber.e("清空缓存失败: ${e.message}")
            }
        }


        val baseUrl = "https://www.wanandroid.com/"
        val retrofit by lazy { createRetrofit() }
        private fun createRetrofit(): Retrofit {
            return Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build()
        }

        val api by lazy { getNetApi() }
        private fun getNetApi(): NetApi {
            return retrofit.create(NetApi::class.java)
        }
    }
} 